package exam;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class LoadResource {
    private LoadResource(){}
    public static LoadResource getInstance(){
        return Instance.instance;
    }
    private static class Instance{
        private static LoadResource instance=new LoadResource();
    }

    private final String STUDENT="StudentName.txt";
    private final String PROBLEM="ada.txt";
    private final AtomicInteger ai=new AtomicInteger(1);

    //缓存
    private List<String> students;
    private List<Problem> problems;

    public List<String> loadStudents(){
        try {
            //判断缓存中是否有值如果没有就去拿  如果有就直接取
            if (students != null && students.size()>0){
                return this.students;
            }

            this.students=loadResource(STUDENT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return this.students;
    }

    public List<Problem> loadProblems(){
        try {
            if (this.problems !=null && this.problems.size() > 0){
                return this.problems;
            }
            List<String> strings = loadResource(PROBLEM);
            this.problems = strings.stream()
                    .map(t -> new Problem(ai.getAndIncrement(), t))
                    .collect(Collectors.toList());

        } catch (IOException e) {
            e.printStackTrace();
        }
        return this.problems;
    }

    private List<String> loadResource(String path) throws IOException {
        List<String> list=new ArrayList<>();
        Reader reader=null;
        BufferedReader bufferedReader=null;
        try {
            reader=new FileReader(path);
            bufferedReader=new BufferedReader(reader);
            String line;
            while ((line=bufferedReader.readLine())!=null){
                list.add(line);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bufferedReader !=null) bufferedReader.close();
        }
        return list;
    }
}
